<?php

/*

*/

if (!defined('IN_ELS'))
{
    die('Hacking attempt');
}
class base {

	var $db;
	var $ip;
	var $view;
	var $log;
	/**
	 * basic
	 *
	 */
	function base() {
		$this->init_db();
		$this->init_log();
		$this->init_template();
	}

	/**
	 * database
	 *
	 */
	function init_db() {
		require_once ELS_ROOT.'lib/db.class.php';
		$this->db = new db();
		$this->db->connect(UC_DBHOST, UC_DBUSER, UC_DBPW, UC_DBNAME, UC_DBCHARSET, UC_DBCONNECT, UC_DBTABLEPRE);
	}
	
	/**
	 * ip
	 *
	 */
	function init_ip() {
		require_once ELS_ROOT.'lib/ip.class.php';
		$this->ip = new ip();
		
		require ELS_ROOT.'lib/ip.php';
		//*ipLocation class end
		$myobj=new ipLocation($_REQUEST);
		$ip=$myobj->getIP();
		$address=$myobj->getaddress($ip);
		$myobj=NULL;
		$ip_add =  mb_convert_encoding($address["area1"], "UTF-8", "GBK");
		$ip_svr =  mb_convert_encoding($address["area2"], "UTF-8", "GBK");
		$str="<span class='orange'>".$ip."</span>&nbsp;&nbsp;来自:".$ip_add." ".$ip_svr;
		$_REQUEST["ipstr"] = $str;
	}
	
	/**
	 * ip
	 *
	 */
	function init_log() {
		require_once ELS_ROOT.'lib/loger.class.php';
		$this->log = new loger();
	}
	
	/**
	 * template
	 *
	 */
	function init_template() {
		require_once ELS_ROOT.'lib/template.class.php';
		$this->view = new template();
	}
	/**
	 * postValue
	 *
	 */
	 function getPostValue($postName){
	 	$postValue=array();	
	 	foreach($postName as $name){
	 		$postValue[$name]=$_POST[$name];	
	 	}	
	 	return $postValue;
	}
	/**
	 * jsonPos
	 *
	 */
	function jsonPost(){
		if(!empty($_POST['json'])){
			return true;
		}else{
			return false;
		}
	}
	/**
	 * redirect
	 *
	 */
	function pageRedirect($path){
		echo "<script>window.location='".$path."'</script>"; 
	}
	/**
	 * pagePost
	 *
	 */
	function pagePost(){
		if(!empty($_POST['submit'])){
			return true;
		}else{
			return false;
		}
	}
	/**
	 * randomFilename
	 *
	 */
	function randomFilename(){
        $str = '';
        for($i = 0; $i < 9; $i++)
        {
            $str .= mt_rand(0, 9);
        }
        return time("data")."_" . $str;
    }
    
     /**
	 * dbInsert
	 *
	 */
	 function dbInsert($table,$data){
	 	 $sqlStr="INSERT INTO ".$table." SET ";
	 	 $num=0;
	 	 foreach($data as $k=>$d){
	 	 	 if($num==0){
	 	 	 	 $sign=" ";$num++;
	 	 	 }else{
	 	 	 	 $sign=" , ";
	 	 	 }
	 	 	 $sqlStr=$sqlStr.$sign.$k."='$d'";
	 	 }
	 	 $num++;
	 	 return $this->db->query($sqlStr);
	 }
     /**
	 * dbUpdate
	 *
	 */
	 function dbUpdate($table,$data,$where){
	 	 $sqlStr="UPDATE ".$table." SET ";
	 	 $num=0;
	 	 foreach($data as $k=>$d){
	 	 	 if($num==0){
	 	 	 	 $sign=" ";$num++;
	 	 	 }else{
	 	 	 	 $sign=" , ";
	 	 	 }
	 	 	 $sqlStr=$sqlStr.$sign.$k."='$d'";
	 	 }
	 	 $sqlStr=$sqlStr." where ".$where;
	 	 $num++;
	 	 return $this->db->query($sqlStr);
	 }
	/**
	 * dbUpdate
	 *
	 */
	 function dbDelete($table,$where){
	 	 $sqlStr="DELETE FROM ".$table." where ".$where;
	 	 return $this->db->query($sqlStr);
	 }
	 
	 //错误输出
	 function setErrInfo($key,$value){
		$this->view->assign($key,$value);
	}
	
	/**
	 * 截取UTF-8编码下字符串的函数
	 *
	 * @param   string      $str        被截取的字符串
	 * @param   int         $length     截取的长度
	 * @param   bool        $append     是否附加省略号
	 *
	 * @return  string
	 */
	function sub_str($str, $length = 0, $append = true)
	{
	    $str = trim($str);
	    $strlength = strlen($str);

	    if ($length == 0 || $length >= $strlength)
	    {
	        return $str;
	    }
	    elseif ($length < 0)
	    {
	        $length = $strlength + $length;
	        if ($length < 0)
	        {
	            $length = $strlength;
	        }
	    }

	    if (function_exists('mb_substr'))
	    {
	        $newstr = mb_substr($str, 0, $length, 'UTF-8');
	    }
	    elseif (function_exists('iconv_substr'))
	    {
	        $newstr = iconv_substr($str, 0, $length, 'UTF-8');
	    }
	    else
	    {
	        $newstr = trim_right(substr($str, 0, $length));
	    }

	    if ($append && $str != $newstr)
	    {
	        $newstr .= '...';
	    }

	    return $newstr;
	}

	/**
	 * 去除字符串右侧可能出现的乱码
	 *
	 * @param   string      $str        字符串
	 *
	 * @return  string
	 */
	function trim_right($str)
	{
	    $length = strlen(preg_replace('/[\x00-\x7F]+/', '', $str)) % 3;

	    if ($length > 0)
	    {
	        $str = substr($str, 0, 0 - $length);
	    }

	    return $str;
	}

	/**
	 * 计算字符串的长度（汉字按照两个字符计算）
	 *
	 * @param   string      $str        字符串
	 *
	 * @return  int
	 */
	function str_len($str)
	{
	    $length = strlen(preg_replace('/[\x00-\x7F]/', '', $str));

	    if ($length)
	    {
	        return strlen($str) - $length + intval($length / 3) * 2;
	    }
	    else
	    {
	        return strlen($str);
	    }
	}
	
	//******************************************************************************
	// function name:	CheckTableId
	// parameter	:	$TableName		Table name
	// return		:	New id 
	// memo			:	Create new primary key of table 
	//******************************************************************************
	function CheckTableId ($TableName) 
 	{     
		$dataArray=$this->db->fetch_first("SELECT keynumber FROM table_key WHERE keyname = '$TableName'");

		if (empty($dataArray))
		{	$d=array();
			$d['keynumber']=1;
			$d['keyname']=$TableName;
			$this->dbInsert('table_key',$d);
		  	return 1;
		}else
		{
			$dataArray['keynumber']=$dataArray['keynumber']+1;
			$this->dbUpdate("table_key",$dataArray,"keyname ='$TableName'");
		  	return $dataArray['keynumber'];
		}
	}
	
	/*
		名称：uploadFlash
		功能：上传flash文件
		备注：需要追加存在判断
	*/
	function uploadObject($file,$dir,$type,$name="null"){
		if($name=="null"){
			$dir_name=$this->randomFilename().".".$type;
		}else{
			$dir_name=$name.".".$type;
		}
		$dir=$dir.$dir_name;
		$upvalue = move_uploaded_file($file["tmp_name"],$dir);
		if (!$upvalue){
			return "";
		}else{
			return $dir_name;
		}
	}
	
	/*
		名称：uploadFlash
		功能：删除文件
		备注：需要追加存在判断
	*/
	function deleteFile($file){
		if(file_exists($file)){
			return unlink($file);
		}
		return false;
	}
	
	//删除文件夹及所有文件
	function delfile($dir) {
		if (is_dir($dir)) {
			$dh=opendir($dir);//打开目录  //列出目录中的所有文件并去掉 . 和 ..  
			while (false !== ( $file = readdir ($dh))) {
				if($file!="." && $file!="..") {
					$fullpath=$dir."/".$file;
					if(!is_dir($fullpath)) {
						unlink($fullpath);//删除目录中的所有文件
					} else {
						$this->delfile($fullpath);
					}
				}
			}
			closedir($dh);
			if(rmdir($dir)) {
				return true;
			} else {
				return false;
			}
		}
	}
	
	/**
	 * 加载相应的 Model, 存入 $_ENV 超级全局变量
	 *
	 * @param string $model 模块名称
	 * @param 该模块相对的基类 $base 默认为该基类
	 * @return 此处不需要返回
	 */
	function load($model, $base = NULL) {
		$base = $base ? $base : $this;
		if(empty($_ENV[$model])) {
			require_once ELS_ROOT."model/".$model."_model.php";
			eval('$_ENV[$model] = new '.$model.'base();');
		}
		return $_ENV[$model];
	}
	
	//******************************************************************************
	// function name:	replaceHtmlToAdditional
	// parameter	:	$htmlstr			Input HTML	
	// return		:  
	// memo			:	Conversion  HTML to additional of HTML
	//******************************************************************************
	function replaceHtmlToAdditional($htmlstr){
		$str = str_replace("&"        	, "&amp;"				, $htmlstr);
		$str = str_replace("<"      	, "&lt;"  				, $str);
		$str = str_replace(">"      	, "&gt;"  				, $str);
		$str = str_replace("'"     		, "&#39;" 				, $str);
		$str = str_replace("\""     	, "&quot;"				, $str);
		$str = str_replace("\r\n"     	, "<br>"				, $str);
		$str = str_replace("\n"     	, "<br>"				, $str);
		$str = str_replace("…" 			, "&#8230;"				, $str);
		$str = str_replace("‾" 			, "&#8254;"				, $str);
		$str = str_replace("−" 			, "&#8722;"				, $str);
		$str = str_replace("¯" 			, "&#175;"				, $str);
		
		return $str;
	}
	
	//from millsecond to hh:ii:ss
	function formatStr($millsecond){
		$second = round($millsecond/1000);
		// < 60
		if($second < 60){
			if($second < 10){
				$second = "0".$second;
			}
			return "00:".$second;
		}else{
			$yushu = $second%60;
			$minutes = round($second/60);
			if($yushu != 0 && $yushu > 30){
				$minutes--;
			}
		
			if($minutes < 10){
				$minutes = "0".$minutes;
			}
		
			if($yushu < 10){
				$yushu = "0".$yushu;
			}
			return $minutes.":".$yushu;
		}
	}
	
	//from second to hh小时ii分钟ss秒
	function interval_time($time){
        $days = $this->interval_day($time);        //多少天 
        $hour = $this->interval_hour($time-86400*$days); 
        $minute = $this->interval_minute($time-86400*$days-3600*$hour); 
        $second = $this->interval_second($time-86400*$days-3600*$hour-60*$minute); 
        
        $str = ""; 
        $str.= $days ? $days."天":""; 
        $str.= $hour ? $hour."小时":""; 
        $str.= $minute ? $minute."分":""; 
        $str.= $second ? $second."秒":""; 
        return $str;
    }
    function interval_day($time){ 
        if ($time>=86400){ 
            return floor($time/86400);        //多少天 
        } 
    }
    function interval_hour($time){ 
        if ($time>=3600 and $time<86400){ 
            return floor($time/3600);        //多少小时 
        } 
    } 
    function interval_minute($time){ 
        if ($time>=60 and $time<3600){ 
            return floor($time/60);        //多少分钟 
        } 
    }
    function interval_second($time){ 
        if ($time>0 and $time<60){ 
            return $time;        //多少秒 
        } 
    }
	
	function getCurrTimeLine(){
		$mtime = explode(' ', microtime());
		return $mtime[1];
	}
	//时间格式化
	function sgmdate($dateformat, $timestamp='', $format=0) {
		global $_SCONFIG, $_SGLOBAL;
		$_SCONFIG['timeoffset'] = 8;
		//取当前格林威治时间
		$curTime = strtotime(date('Y-m-d H:i:s'));
		if(empty($timestamp)) {
			$timestamp = $curTime;
		}
		$result = '';
		if($format) {
			$time = $curTime - $timestamp;
			if($time > 24*3600) {
				$result = gmdate($dateformat, $timestamp + $_SCONFIG['timeoffset'] * 3600);
			} elseif ($time > 3600) {
				$result = intval($time/3600)."小时前";
			} elseif ($time > 60) {
				$result = intval($time/60)."分钟前";
			} elseif ($time > 0) {
				$result = $time."秒前";
			} else {
				$result = "现在";
			}
		} else {
			$result = gmdate($dateformat, $timestamp + $_SCONFIG['timeoffset'] * 3600);
		}
		return $result;
	}
	
	//字符串时间化
	function sstrtotime($string) {
		global $_SGLOBAL, $_SCONFIG;
		$_SCONFIG['timeoffset'] = 8;
		$time = '';
		if($string) {
			$time = strtotime($string);
			if($this->sgmdate('H:i') != date('H:i')) {
				$time = $time - $_SCONFIG['timeoffset'] * 3600;
			}
		}
		return $time;
	}
	
	// 移动文件
	function move_file($path1,$path2) { 
	   if($path1==""):return false;endif; 
	
	   if($path2=="") {
	     $ext=strrchr($path1,".");
	     $path2=date("dMYHis").$ext; 
	   }
	   ob_start(); 
	   readfile($path1); 
	   $file_tmp = ob_get_contents(); 
	   ob_end_clean();
	   $size = strlen($file_tmp); 
	
	   $fp2=@fopen($path2, "a"); 
	   fwrite($fp2,$file_tmp); 
	   fclose($fp2);
		
	   return $path2;
	}
	
	// 日志
	function log_write($message){
		$this->log->log_login($message);
	}
	
	function sendMail($toemail,$mailsubject,$mailbody){
		
		require("lib/smtp.class.php");
		##########################################
		$smtpserver = SMTPSERVER;//SMTP服务器
		$smtpserverport =25;//SMTP服务器端口
		$smtpusermail = SMTPUSERMAIL;//SMTP服务器的用户邮箱
		$smtpemailto = $toemail;//发送给谁
		$smtpuser = SMTPUSER;//SMTP服务器的用户帐号
		$smtppass = SMTPPASS;//SMTP服务器的用户密码
		$mailsubject = "=?UTF-8?B?".base64_encode($mailsubject)."?=";//邮件主题
		$mailtype = "HTML";//邮件格式（HTML/TXT）,TXT为文本邮件
		##########################################
		
		$smtp = new smtp($smtpserver,$smtpserverport,true,$smtpuser,$smtppass);//这里面的一个true是表示使用身份验证,否则不使用身份验证.
		$smtp->debug = False;//是否显示发送的调试信息
		$smtp->sendmail($smtpemailto, $smtpusermail, $mailsubject, $mailbody, $mailtype);
	}

	//cookie设置
	function ssetcookie($var, $value, $life=0) {
		global $_SGLOBAL, $_SC, $_SERVER;
		$_SGLOBAL['timestamp'] = date("Y-m-d H:i:s",time()+8*3600);
		setcookie($_SC['cookiepre'].$var, $value, $life?($_SGLOBAL['timestamp']+$life):0, '/', '', $_SERVER['SERVER_PORT']==443?1:0);
	}
	
	//获取字符串
	function getstr($string, $length, $in_slashes=0, $out_slashes=0, $censor=0, $bbcode=0, $html=0) {
		global $_SC, $_SGLOBAL;
	
		$string = trim($string);
	
		if($in_slashes) {
			//传入的字符有slashes
			$string = $this->sstripslashes($string);
		}
		if($html < 0) {
			//去掉html标签
			$string = preg_replace("/(\<[^\<]*\>|\r|\n|\s|\[.+?\])/is", ' ', $string);
			$string = $this->shtmlspecialchars($string);
		} elseif ($html == 0) {
			//转换html标签
			$string = $this->shtmlspecialchars($string);
		}
		if($censor) {
			//词语屏蔽
			@include_once('lib/data_censor.php');
			if($_SGLOBAL['censor']['banned'] && preg_match($_SGLOBAL['censor']['banned'], $string)) {
				$this->showmessage("对不起，发布的信息中包含站点屏蔽的文字", "javascript:history.go(-1);");
			} else {
				$string = empty($_SGLOBAL['censor']['filter']) ? $string :
					@preg_replace($_SGLOBAL['censor']['filter']['find'], $_SGLOBAL['censor']['filter']['replace'], $string);
			}
		}
		if($length && strlen($string) > $length) {
			//截断字符
			$wordscut = '';
			//strtolower:全部转换为小写字母，$_SC['charset']:在ucenter里已经写死就是utf-8
			$_SC['charset'] = 'utf-8';
			if(strtolower($_SC['charset']) == 'utf-8') {
				//utf8编码
				$n = 0;
				$tn = 0;
				$noc = 0;
				while ($n < strlen($string)) {
					$t = ord($string[$n]);
					if($t == 9 || $t == 10 || (32 <= $t && $t <= 126)) {
						$tn = 1;
						$n++;
						$noc++;
					} elseif(194 <= $t && $t <= 223) {
						$tn = 2;
						$n += 2;
						$noc += 2;
					} elseif(224 <= $t && $t < 239) {
						$tn = 3;
						$n += 3;
						$noc += 2;
					} elseif(240 <= $t && $t <= 247) {
						$tn = 4;
						$n += 4;
						$noc += 2;
					} elseif(248 <= $t && $t <= 251) {
						$tn = 5;
						$n += 5;
						$noc += 2;
					} elseif($t == 252 || $t == 253) {
						$tn = 6;
						$n += 6;
						$noc += 2;
					} else {
						$n++;
					}
					if ($noc >= $length) {
						break;
					}
				}
				if ($noc > $length) {
					$n -= $tn;
				}
				$wordscut = substr($string, 0, $n);
			} else {
				for($i = 0; $i < $length - 1; $i++) {
					if(ord($string[$i]) > 127) {
						$wordscut .= $string[$i].$string[$i + 1];
						$i++;
					} else {
						$wordscut .= $string[$i];
					}
				}
			}
			$string = $wordscut;
		}
		if($bbcode) {
			include_once('lib/function_bbcode.php');
			$string = bbcode($string, $bbcode);
		}
		if($out_slashes) {
			$string = $this->saddslashes($string);
		}
		return trim($string);
	}
	
	//去掉slassh
	function sstripslashes($string) {
		if(is_array($string)) {
			foreach($string as $key => $val) {
				$string[$key] = $this->sstripslashes($val);
			}
		} else {
			$string = stripslashes($string);
		}
		return $string;
	}
	
	//取消HTML代码
	function shtmlspecialchars($string) {
		if(is_array($string)) {
			foreach($string as $key => $val) {
				$string[$key] = $this->shtmlspecialchars($val);
			}
		} else {
			$string = preg_replace('/&amp;((#(\d{3,5}|x[a-fA-F0-9]{4})|[a-zA-Z][a-z0-9]{2,5});)/', '&\\1',
				str_replace(array('&', '"', '<', '>'), array('&amp;', '&quot;', '&lt;', '&gt;'), $string));
		}
		return $string;
	}
	
	//SQL ADDSLASHES
	function saddslashes($string) {
		if(is_array($string)) {
			foreach($string as $key => $val) {
				$string[$key] = $this->saddslashes($val);
			}
		} else {
			$string = addslashes($string);
		}
		return $string;
	}

	//获取在线IP
	function getonlineip($format=0) {
		global $_SGLOBAL;
	
		if(empty($_SGLOBAL['onlineip'])) {
			if(getenv('HTTP_CLIENT_IP') && strcasecmp(getenv('HTTP_CLIENT_IP'), 'unknown')) {
				$onlineip = getenv('HTTP_CLIENT_IP');
			} elseif(getenv('HTTP_X_FORWARDED_FOR') && strcasecmp(getenv('HTTP_X_FORWARDED_FOR'), 'unknown')) {
				$onlineip = getenv('HTTP_X_FORWARDED_FOR');
			} elseif(getenv('REMOTE_ADDR') && strcasecmp(getenv('REMOTE_ADDR'), 'unknown')) {
				$onlineip = getenv('REMOTE_ADDR');
			} elseif(isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], 'unknown')) {
				$onlineip = $_SERVER['REMOTE_ADDR'];
			}
			preg_match("/[\d\.]{7,15}/", $onlineip, $onlineipmatches);
			$_SGLOBAL['onlineip'] = $onlineipmatches[0] ? $onlineipmatches[0] : 'unknown';
		}
		if($format) {
			$ips = explode('.', $_SGLOBAL['onlineip']);
			for($i=0;$i<3;$i++) {
				$ips[$i] = intval($ips[$i]);
			}
			return sprintf('%03d%03d%03d', $ips[0], $ips[1], $ips[2]);
		} else {
			return $_SGLOBAL['onlineip'];
		}
	}

	//屏蔽html
	function checkhtml($html) {
		$html = stripslashes($html);
			
		preg_match_all("/\<([^\<]+)\>/is", $html, $ms);

		$searchs[] = '<';
		$replaces[] = '&lt;';
		$searchs[] = '>';
		$replaces[] = '&gt;';
		
		if($ms[1]) {
			$allowtags = 'img|a|font|div|table|tbody|caption|tr|td|br|p|b|strong|i|u|em|span|ol|ul|li|blockquote|object|param|embed';//允许的标签
			$ms[1] = array_unique($ms[1]);
			foreach ($ms[1] as $value) {
				$searchs[] = "&lt;".$value."&gt;";
				$value = $this->shtmlspecialchars($value);
				$value = str_replace(array('\\','/*'), array('.','/.'), $value);
				$value = preg_replace(array("/(javascript|script|eval|behaviour|expression)/i", "/(\s+|&quot;|')on/i"), array('.', ' .'), $value);
				if(!preg_match("/^[\/|\s]?($allowtags)(\s+|$)/is", $value)) {
					$value = '';
				}
				$replaces[] = empty($value)?'':"<".str_replace('&quot;', '"', $value).">";
			}
		}
		$html = str_replace($searchs, $replaces, $html);
		$html = addslashes($html);
		
		return $html;
	}

	//连接字符
	function simplode($ids) {
		return "'".implode("','", $ids)."'";
	}
	
	//返回数字
	function reNum($oldValue,$v){
		if(is_numeric($oldValue)){
			return $oldValue;
		}else{
			return $v;
		}
	}
	
	//消息处理
	function showmessage($msgkey, $url_forward='') {
		$this->view->assign('message' ,$msgkey);
		$this->view->assign('url' ,$url_forward);
		$this->view->display("message");
		exit();
	}

	//获取数目
	function getcount($tablename, $wherearr, $get='COUNT(*)') {
		if(empty($wherearr)) {
			$wheresql = '1';
		} else {
			$wheresql = $mod = '';
			foreach ($wherearr as $key => $value) {
				$wheresql .= $mod."`$key`='$value'";
				$mod = ' AND ';
			}
		}
		return $this->db->result_first("SELECT $get FROM $tablename WHERE $wheresql LIMIT 1");
	}
	
	// 函数名: writefile
	// 功能: 创建新文件，并写入内容，如果指定文件名已存在，那将直接覆盖
	// 参数: $file -- 新文件名
	// $source   文件内容
	/**************************************************************************/
	function writefile($file,$source){
	     if($fp==fopen($file,'w')){
	         $filesource=fwrite($fp,$source);
	         fclose($fp);
	         return $filesource;
	     }
	     else
	         return false;
	}
	
	//获取自定长度字符串
	function getGName($groupname,$len){
		$i=0;
		$j=0;
		$str="";
		while($i<$len){
			if($this->countCnChars(mb_substr($groupname,$j,1,"UTF-8"))>0){
				$i=$i+2;
			}else{
				$i=$i+1;	
			}
			$str.=mb_substr($groupname,$j,1,"UTF-8");
			$j=$j+1;
		}
		if($this->getLengthGBK($groupname)>$len){
			$str=$str."..";
		}
		return $str;
	}
	
	//获取自定长度
	function getLengthGBK($str){
		$len=strlen($str);
		$i=0;
		$j=0;
		$x=0;
		while($i<$len){
		 	if($this->countCnChars(mb_substr($str,$j,1,"UTF-8"))>0){
		        $i=$i+3;
		        $x=$x+2;
		     }else{
		        $i+=1;
		        $x=$x+1;
		  	}
		  $j=$j+1;
		}
		return $x;
	}
	
	//输入的是中文还是英文
	function countCnChars($str){
	    $str = str_replace("　"," ",$str);//替换全角空格
	    $byte = strlen($str);
	    $english_num = 0;
	    $chinese_num = 0;
	    $other_num = 0;
	    $flag = false;
	    for($i=0; $i<$byte;){
	        $ch=substr($str,$i,1);
	        if(ord($ch)>0x80){
	            if($flag){
	                $english_num++;
	                $flag = false;
	            }
	            $chinese_num ++;
	            $i += 2;
	        } else {
	            if(ord($ch)>=65 && ord($ch)<=90 || ord($ch)>=97 && ord($ch)<=122){
	                $flag = true;
	            } else {
	                if($flag){
	                    $english_num++;
	                }
	                $flag = false;
	                $other_num++;
	            }
	            $i++;
	        }
	    }
	    return $chinese_num;
	}
	
	//格式化大小函数
	function formatsize($size) {
		$prec=3;
		$size = round(abs($size));
		$units = array(0=>" B ", 1=>" KB", 2=>" MB", 3=>" GB", 4=>" TB");
		if ($size==0) return str_repeat(" ", $prec)."0$units[0]";
		$unit = min(4, floor(log($size)/log(2)/10));
		$size = $size * pow(2, -10*$unit);
		$digi = $prec - 1 - floor(log($size)/log(10));
		$size = round($size * pow(10, $digi)) * pow(10, -$digi);
		return $size.$units[$unit];
	}
	//把数据替换成图片
	function replaceVoteData($vote){
		$str = str_replace("0", "<img src='images/num_0.gif'>", $vote);
		$str = str_replace("1", "<img src='images/num_1.gif'>", $str);
		$str = str_replace("2", "<img src='images/num_2.gif'>", $str);
		$str = str_replace("3", "<img src='images/num_3.gif'>", $str);
		$str = str_replace("4", "<img src='images/num_4.gif'>", $str);
		$str = str_replace("5", "<img src='images/num_5.gif'>", $str);
		$str = str_replace("6", "<img src='images/num_6.gif'>", $str);
		$str = str_replace("7", "<img src='images/num_7.gif'>", $str);
		$str = str_replace("8", "<img src='images/num_8.gif'>", $str);
		$str = str_replace("9", "<img src='images/num_9.gif'>", $str);
		
		return $str;
	}
	//图片缩放
	function resizeImage($im,$maxwidth,$maxheight,$name,$filetype="")
	{
	    $pic_width = @imagesx($im);
	    $pic_height = @imagesy($im);

	    if(($maxwidth && $pic_width > $maxwidth) || ($maxheight && $pic_height > $maxheight))
	    {
	        if($maxwidth && $pic_width>$maxwidth)
	        {
	            $widthratio = $maxwidth/$pic_width;
	            $resizewidth_tag = true;
	        }

	        if($maxheight && $pic_height>$maxheight)
	        {
	            $heightratio = $maxheight/$pic_height;
	            $resizeheight_tag = true;
	        }

	        if($resizewidth_tag && $resizeheight_tag)
	        {
	            if($widthratio<$heightratio)
	                $ratio = $widthratio;
	            else
	                $ratio = $heightratio;
	        }

	        if($resizewidth_tag && !$resizeheight_tag)
	            $ratio = $widthratio;
	        if($resizeheight_tag && !$resizewidth_tag)
	            $ratio = $heightratio;

	        $newwidth = $pic_width * $ratio;
	        $newheight = $pic_height * $ratio;

	        if(function_exists("imagecopyresampled"))
	        {
	            $newim = @imagecreatetruecolor($newwidth,$newheight);
	           @imagecopyresampled($newim,$im,0,0,0,0,$newwidth,$newheight,$pic_width,$pic_height);
	        }
	        else
	        {
	            $newim = @imagecreate($newwidth,$newheight);
	           @imagecopyresized($newim,$im,0,0,0,0,$newwidth,$newheight,$pic_width,$pic_height);
	        }
			
			if($filetype){
				$name = $name.$filetype;
			} else {
				$name = $name;
			}
	        @imagejpeg($newim,$name);
	        @imagedestroy($newim);
	    }
	    else
	    {
	        if($filetype){
				$name = $name.$filetype;
			} else {
				$name = $name;
			}
	        @imagejpeg($im,$name);
	    }           
	}
	// 调用公共底部
	function get_footer()
	{
		$sql_content = $this->db->fetch_all("select id,parent_id,name,url from gnw_footer where parent_id=0 and is_ok=1");
		foreach($sql_content as $k=>$v)
		{
			$sql_content[$k]['child_list'] = $this->db->fetch_all("select id,parent_id,name,url from gnw_footer where parent_id=".$v['id']." and is_ok=1");
			
		}
		return $sql_content;
	}
	//调用公共合作机构
	function get_agency()
	{
		$sql_content = $this->db->fetch_all("select title,url,s_img_url from gnw_agency where is_ok=2 order by agency_id desc limit 8");
		return $sql_content;
	}
}

?>